from flask import Flask, Response
from flask_caching import Cache
import board
import adafruit_dht
import json

app = Flask(__name__)
app.config['CACHE_TYPE'] = 'simple'
app.config['CACHE_DEFAULT_TIMEOUT'] = 2  # Cache timeout in seconds
cache = Cache(app)
dhtDevice = adafruit_dht.DHT22(board.D4)


# Function to get temperature and humidity
def get_temp_and_hum():

    d_temp = dhtDevice.temperature
    d_hum = dhtDevice.humidity
    d_hum = round(d_hum, 2)
    d_temp = round(d_temp, 2)
    data = [d_temp, d_hum]
    return data


# Endpoint to get temperature and humidity
@app.route('/api/gettmp', methods=["GET", "POST"])
@cache.cached()
def get_temperature():
    data = get_temp_and_hum()
    return Response(json.dumps(data), mimetype='application/json')


if __name__ == '__main__':
    app.run('0.0.0.0', port=5005)
